<template>
    <div class="white-box" v-loading.fullscreen="loading">
      <el-form ref="formRef" :model="formData" :rules="formRule" label-width="120px">
        <title-more title="基础信息"></title-more>
        <el-form-item label="角色名称" prop="roleName" required>
          <el-input v-model.trim="formData.roleName" clearable placeholder="请输入角色名称" :maxlength="20" style="max-width: 300px"/>
        </el-form-item>
        <el-form-item label="角色权限key" prop="roleKey" required>
          <el-input v-model.trim="formData.roleKey" clearable placeholder="请输入角色权限key" :maxlength="20" style="max-width: 300px"/>
        </el-form-item>
        <el-form-item label="数据范围" prop="dataScope">
          <el-select v-model="formData.dataScope" placeholder="请选择数据范围" style="max-width: 300px">
            <el-option :label="item.label" :value="item.value" v-for="(item, index) in selectOptions.dataScope" :key="index"/>
          </el-select>
        </el-form-item>
        <el-form-item label="角色等级" prop="level">
          <div style="width: 100%">
            <el-input-number
                v-model="formData.level"
                class="mx-4"
                :min="1"
                :max="99"
                controls-position="right"
                :precision="0"
            />
            <div>
              <el-text type="danger">数值越小，等级越高；0为最高等级（超级管理员，不可添加与修改）</el-text>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model.trim="formData.note" clearable placeholder="请输入备注" style="max-width: 300px"/>
        </el-form-item>
        <el-form-item label="删除" prop="deletable">
          <el-radio-group v-model="formData.deletable">
            <el-radio :value="0">可以删除</el-radio>
            <el-radio :value="1">不可以删除</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <title-more title="分配菜单"></title-more>
        <div class="mra-box">
          <loading-small v-if="treeSelectLoading"></loading-small>
          <el-empty description="暂无权限配置项" v-if="selectOptions.menuSids === 0 && !treeSelectLoading" />
          <template v-if="selectOptions.menuSids.length > 0 && !treeSelectLoading">
            <el-tree ref="menuSidsTreeRef" :data="selectOptions.menuSids" show-checkbox node-key="sid" default-expand-all :props="treeDefaultProps" />
          </template>
        </div>
        <div class="foot-btn flexs-center">
          <el-button type="primary" size="large" :loading="btnLoading" @click="submitForm(formRef)">{{sid?'确认修改':'确认添加'}}</el-button>
        </div>
      </el-form>
    </div>
    <go-back/>
</template>

<script setup>
import {getCurrentInstance, ref, onMounted, onBeforeUnmount, reactive} from "vue"
import { useRouter,useRoute } from "vue-router"
import LoadingSmall from "@components/LoadingSmall.vue"
import GoBack from "@components/GoBack.vue"
import TitleMore from "@components/title-more.vue";
const router = useRouter()
const route = useRoute()
const sid = route.query.sid || ""
const { proxy } = getCurrentInstance()

const btnLoading = ref(false)
const loading = ref(false)
const formRef = ref(null)
const formData = reactive({
  dataScope: '',
  deletable: '',
  level: 1,
  menuSids: [],
  note:'',
  roleKey:'',
  roleName:'',
  status:''
})
const formRule = reactive({
  roleName: [{required: true, message: "请输入", trigger: "blur"}],
  roleKey: [{required: true, message: "请输入", trigger: "blur"}],
})
const selectOptions = reactive({
  dataScope:[
    {label:'全部',value:10},
    {label:'本级及以下',value:20},
    {label:'本级',value:30},
    {label:'仅下级',value:40},
    {label:'自定义',value:50},
  ],
  menuSids:[]
})
const detail = reactive({})
onMounted(async () => {
  if(sid){
    await getDetail()
  }
  await getTreeSelect();
    // roles.value = sessionStorage.getItem("ROLES") ? JSON.parse(sessionStorage.getItem("ROLES")) : null
    // if (roles.value != null) {
    //     value_text.value = roles.value.role_name
    //     getMenu()
    // } else {
    //     proxy.$message({ message: "异常访问，自动返回上一页", type: "error" })
    //     router.go(-1)
    // }
})
const getDetail = async () =>{
  loading.value = true
  await proxy.$axios
      .get(`/roles/${sid}`)
      .then((res) => {
        if (res.data.code == 200) {
          let result = res.data.data
          for (let key in formData) {
            formData[key] = result[key]
          }
        } else {
          proxy.$message({message: res.data.msg, type: "error"})
        }
      }).catch((err) => {

      }).finally(()=>{
        loading.value = false
      })
}
const filterMenuSids = (parent,menuSids) =>{
  if(!menuSids.includes(parent.sid)){
    return menuSids;
  }
  if(parent.children && parent.children.length>0){
    parent.children.forEach(item=>{
      if(item.children && item.children.length>0){
        menuSids = filterMenuSids(item,menuSids)
      }else{
        let allChildrenSid = parent.children.map((c)=>c.sid);
        let flag = true;
        allChildrenSid.forEach(sid=>{
          if(!menuSids.includes(sid)){
            flag = false;
          }
        })
        if(!flag){
          menuSids = menuSids.filter(sid=> sid !== parent.sid)
        }
      }
    })
  }
  return menuSids;
}

const treeSelectLoading = ref(false)
const getTreeSelect = async () => {
  treeSelectLoading.value = true
  await proxy.$axios
      .get('/menus/treeSelect')
      .then((res) => {
        if (res.data.code == 200) {
          let result = res.data.data
          selectOptions.menuSids = result
          let checkedMenuSids = JSON.parse(JSON.stringify(formData.menuSids));
          result.forEach(item=>{
            checkedMenuSids = filterMenuSids(item,checkedMenuSids)
          })
          setTimeout(() => {
            menuSidsTreeRef.value.setCheckedKeys(checkedMenuSids, false) // 设置选中的节点
          }, 100)
        } else {
          proxy.$message({message: res.data.msg, type: "error"})
        }
      })
      .catch((error) => {

      }).finally(()=>{
        treeSelectLoading.value = false
      })
}

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      let nodes = menuSidsTreeRef.value.getCheckedNodes(false, true) // 获取选中node数组
      let menuSids = menuSidsTreeRef.value.getCheckedKeys(true)
      // formData.menuSids = nodes.map(v=>v.sid)
      formData.menuSids = menuSids
      btnLoading.value = true;
      let method = 'post';
      let url = '/roles'
      if(sid){
        method = 'put';
        url += `/${sid}`
      }
      proxy.$axios[method](url,formData)
          .then((res) => {
            btnLoading.value = false
            if (res.data.code == 200) {
              proxy.$message({message: "保存成功！", type: "success",onClose:()=>router.go(-1)})
            } else {
              proxy.$message({message: res.data.msg, type: "error"})
            }
          })
          .catch((err) => {
            btnLoading.value = false
          })
    }
  })
}

onBeforeUnmount(() => {
    menuSidsTreeRef.value = null
})
const menuSidsTreeRef = ref(null)
const treeDefaultProps = ref({
    children: "children",
    label: "menuName",
})
</script>
<script>
export default {
    name: "ManageRoleEdit",
}
</script>

<style lang="less" scoped>
//.white-content {
//    padding-bottom: 40px;
//}
//
:deep(.el-tree-node) {
    //box-shadow: 0 0px 6px rgba(0, 0, 0, 0.06);
    //padding: @padding-md @padding-md;
    //border-radius: @radius-xs;
    //margin-bottom: @margin-mdl;
    flex: none;
    width: 100%;

    & .el-tree-node {
        box-shadow: 0 0px 0px;
        padding: 0;
        margin-bottom: 0;
        border-radius: 0;
    }

    .el-checkbox__inner {
        width: 18px;
        height: 18px;

        &::after {
            width: 4px;
            height: 9px;
            left: 6px;
            top: 1px;
        }
    }

    .el-tree-node__content {
        margin-bottom: @margin-xs;
        padding-left: 0;

        &:hover {
            background: none !important;
        }
    }

    .el-tree-node__children {
        display: flex;
        flex-flow: row wrap;
        justify-content: flex-start;
    }
}

.mra-box {
  margin-bottom: 30px;
    //border-radius: @radius-xs;
    //margin: @margin-xl 0px;

    //.mar-item {
    //    box-shadow: 0 0px 6px rgba(0, 0, 0, 0.06);
    //    padding: @padding-md @padding-md 0px;
    //    border-radius: @radius-xs;
    //    margin-bottom: @margin-mdl;
    //
    //    &:last-child {
    //        margin-bottom: 0;
    //    }
    //}
}
</style>
